import {Component, ElementRef, OnInit,Input,ViewChild} from '@angular/core';
import {DrawService, TipService, ModalTipService, ModalService ,HttpService} from 'itcloud-plugin';
import { GetPathService } from '../../get-path.service';
import { Router} from '@angular/router'; //导入router服务
import { ViewReceiverComponent } from '../detail-notice/view-receiver/view-receiver.component';


@Component({
  selector: 'app-detail-notice',
  templateUrl: './detail-notice.component.html',
  styleUrls: ['./detail-notice.component.css']
})
export class DetailNoticeComponent implements OnInit {

  @Input() handler;
  @Input() data;
  pager;
  limit;
  cookies:any;
  infoName:string;
  //tablenew 表格；
  // 表头数据
  headerConfig: Array<any> = [];
  // 表内容数据
  tableData: Array<any> = [];  //所展示的列表内容；
  tableDataAll: Array<any> = [];  //说有的的列表内容上传用；

  //分页功能；
//   pager3 = {
//     total: 0,
//     limit: 5,
//     page: 1,
//   };
  param:any={
        limit: 5,
        page: 1
    };

  public allDetailNotice:any={};
  public detailNotice:any={};
  public detailNoticeList:any=[];
  public detailFiled:any=[];
  public Status:any;
  public aaa:any;
  constructor(private http: HttpService,
              private tipService: TipService,
              private GetPathService: GetPathService,
              private router: Router,
              private modal: ModalService,
              private modalTip: ModalTipService,
              private drawService: DrawService,
  ) { }

  /*取消点击关闭*/
  closeDrawer() {
    this.handler&& this.handler();
  }

  /*关闭公告*/
    closeNotice(){
        this.http.getData({
            url: this.GetPathService.AjaxPath.bulletinServer+`/bulletin/udateStatus?infoId=${this.detailNotice.id}&operation=1`,
        }).subscribe(res => {
            this.tipService.show({
                type: 'success',
                title: '关闭公告成功！',
            });
            this.handler&& this.handler();
        }, err => {
            console.log(err.returnMessage)
        });
    }
  /*
   获取列表公告数据
   * */
  requestData() {
      console.log(this.param);
    this.http.getData({
      url: this.GetPathService.AjaxPath.bulletinServer+`/bulletin/getInfoListById?id=${this.data.id}`,
        search:this.param
    }).subscribe(res => {
      this.allDetailNotice=res['beans'];
      this.detailNotice=res['beans'].infoList;
      this.detailFiled=res['beans'].from;
      this.disposeData(res['beans'].infoMineList);
      this.detailNoticeList=res['beans'].infoMineList;
      //this.limit=res['beans'].count;
      this.pager.total=res['beans'].count;
        if(this.detailNotice.infoType==0){
            this.infoName=`关于${this.detailNotice.infoName}的公告通知`;
        }else if(this.detailNotice.infoType==1){
            this.infoName=`关于${this.detailNotice.infoName}的信息交流`;
        }
        this.getList()
      //console.log(this.allDetailNotice)
    }, err => {
      console.log(err.returnMessage)
    });
  }

    //处理数据
    disposeData(data){
        for(let i=0;i<data.length;i++){
            if(this.detailNotice.infoType==0){ /*公告通知状态*/
                if(data[i].todoStatus==1||data[i].todoStatus==0){
                    data[i].statusName="未阅";
                }else if(data[i].todoStatus==2){
                    data[i].statusName="已阅";
                }
            }else if(this.detailNotice.infoType==1){/*信息交流状态*/
                if(data[i].todoStatus==1||data[i].todoStatus==0){
                    data[i].statusName="待回复";
                }else if(data[i].todoStatus==2||data[i].todoStatus==3){
                    data[i].statusName="已回复";
                }
            }
        }
        this.tableData = data;
    }

  /*接收人批量提醒*/
    sendMessage() {
      let  finallyUserId:string='';
      let  userId:string='';
      let  message:string='';
      for(let i=0; i<this.detailNoticeList.length; i++){
          userId+=`${this.detailNoticeList[i].userId},`;
      }
      for(let k=0;k<userId.length;k++){
          finallyUserId=userId.substr(0,k);
      }
        if(this.detailNotice.infoType==0){ /*公告通知状态*/
            message="未阅";
        }else if(this.detailNotice.infoType==1){/*信息交流状态*/
            message="待回复";
        }

    this.modalTip.openTip({
      typeTitle: '批量提醒',
      backdropCloseable: false,
      icon: '',
      msg: `是否批量短信提醒所有${message}的接收人？`,
      handler: (ev) => {
        if(ev.type==1){
            //console.log(finallyUserId)
            this.http.getData({
                url: this.GetPathService.AjaxPath.bulletinServer+`/bulletin/sendSms?id=${finallyUserId}`,
            }).subscribe(res => {
                this.tipService.show({
                    type: 'success',
                    title: '短信发送成功！',
                });
            }, err => {
                console.log(err.returnMessage)
            });
        }
      }
    });
  }
  /*纸飞机单个提醒*/
    sendOnlyOne(data){
        let message="";
        if(this.detailNotice.infoType==0){ /*公告通知状态*/
            if(data.todoStatus==1||data.todoStatus==0){
                message="是否短信提醒未阅的接收人？";
            }else if(data.todoStatus==2){
                message="是否短信提醒已阅的接收人？";
            }
        }else if(this.detailNotice.infoType==1){/*信息交流状态*/
            if(data.todoStatus==1||data.todoStatus==0){
                message="是否短信提醒待回复的接收人？";
            }else if(data.todoStatus==2||data.todoStatus==3){
                message="是否短信提醒已回复的接收人？";
            }
        }
        this.modalTip.openTip({
            typeTitle: '提醒',
            backdropCloseable: false,
            icon: '',
            msg: message,
            handler: (ev) => {
                if(ev.type==1){
                    this.http.getData({
                        url: this.GetPathService.AjaxPath.bulletinServer+`/bulletin/sendSms?id=${data.userId}`,
                    }).subscribe(res => {
                        this.tipService.show({
                            type: 'success',
                            title: '短信发送成功！',
                        });
                    }, err => {
                        console.log(err.returnMessage)
                    });
                }
            }
        });
    };
    
  /*查看显示驳回*/
  openModalView(dataRequest,datalist) {
      let message='';
      if(this.detailNotice.infoType==0){ /*公告通知状态*/
          message="我的创建 / 公告详情";
      }else if(this.detailNotice.infoType==1){/*信息交流状态*/
          message="我的创建 / 公告详情 / 回复详情";
      }
    const result=this.modal.open({
      title: message,
      component: ViewReceiverComponent,
      backdropCloseable: false,
      handler: (type) => { // 传入侧滑component的方法，在component中用@Input() handler:any;接收
        result.modalInstance.hide();
        this.requestData()
          //alert(this.requestData())
      },
      width: '50%', // 侧滑宽度
      data: {dataRequest,datalist}
    });
  }

  /*驳回*/
  reject(userId){
    this.http.getData({
      url: this.GetPathService.AjaxPath.bulletinServer+`/mineTodo/udateStatus?id=${userId}&type=${this.detailNotice.infoType}&status=${this.detailNotice.infoStatus}`,
    }).subscribe(res => {
        this.tipService.show({
            type: 'success',
            title: '驳回成功！',
        });
        this.requestData()
    }, err => {
        this.tipService.show({
            type: 'success',
            title:err.returnMessage,
        });
    });
  }
  /*接收人列表*/
  /**
   * 初始化表头
   */
  setListHeader() {
    this.headerConfig = [
      {
        field: 'userName',
        title: '姓名',
        width: '20%',
      }, {
        field: 'phone',
        title: '手机号',
        width: '20%',
      }, {
        field: 'organName',
        title: '组织',
        width: '20%',
      }, {
        field: 'todoStatus',
        canSort: false, // 是否可排序
        title: '状态',
        width: '20%',
        hideTitle: true
      },
      {
        field: 'operation',
        title: '操作',
        width: '20%',
        align:'center'
      }
    ];
  };

  sortEvent(ev: any) {
    this.pager = {
      total: 0,
      limit: 5,
      page: 1
    };
    console.log(ev);
    this.param.sortField= ev.sort;
    this.param.sorting= (ev.sort ==='desc' ? '1' : (ev.sort === 'asc' ? '-1' : ''));
    this.requestData();
  }


  //获取接收人列表数据
  getList(){
    setTimeout(() => {
      // this.tableOption.loading = false;
      this.tableDataAll = this.detailNoticeList;
      //计算从tableDataAll数据中 截取当前页数来展示；
      //this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
      //总条数；
      //this.pager3.total=this.tableDataAll.length
    }, 300);

  }
  //删除列表项；
  deleteDemand(dataParam){//console.log(dataParam.id);
    for(let i=0; i<this.tableDataAll.length;i++){
      if(this.tableDataAll[i].id == dataParam.id){
        this.tableDataAll.splice(i,1)
      }
    }
    //计算从tableDataAll数据中 截取当前页数来展示；
    //this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
    //总条数；
    // this.pager3.total=this.tableDataAll.length;
    // if(!this.tableData.length && this.pager3.page >1){   //如果当前页没有数据，页数就减一；
    //   this.pager3.page--;
    //   this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
    // }
  };
  //改变页数；
  nowPageChange(pageNum) {
    //console.log(pageNum);
    this.pager.page = pageNum;
    this.param.page = pageNum;
    this.requestData();
    //计算从tableDataAll数据中 截取当前页数来展示；
    //this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
  };

  /***
   * 时间转换
   *
   *
   * */
  timeStamp(timestamp){
      let Y,M,D,h,m,s;
      let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      //var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      Y = date.getFullYear() + '-';
      M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
      h = (date.getHours() < 10 ? '0'+ date.getHours() : date.getHours()) + ':';
      m = (date.getMinutes() < 10 ? '0'+ date.getMinutes() : date.getMinutes()) + ':';
      s = (date.getSeconds()< 10 ? '0'+ date.getSeconds() : date.getSeconds());
      return Y+M+D+h+m+s;
  }
  /*附件大小转化*/
  conver(limit){
    let size = "";
    if( limit < 0.1 * 1024 ){ //如果小于0.1KB转化成B
      size = limit.toFixed(2) + "B";
    }else if(limit < 0.1 * 1024 * 1024 ){//如果小于0.1MB转化成KB
      size = (limit / 1024).toFixed(2) + "KB";
    }else if(limit < 0.1 * 1024 * 1024 * 1024){ //如果小于0.1GB转化成MB
      size = (limit / (1024 * 1024)).toFixed(2) + "MB";
    }else{ //其他转化成GB
      size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }

    let sizestr = size + "";
    let len = sizestr.indexOf("\.");
    let dec = sizestr.substr(len + 1, 2);
    if(dec == "00"){//当小数点后为00时 去掉小数部分
      return sizestr.substring(0,len) + sizestr.substr(len + 3,2);
    }
    return sizestr;
  }

  ngOnInit() {
    this.requestData();
    this.setListHeader(); //初始化表头；
    this.pager = {
        total: 0,
        limit: 5,
        page: 1
    };
    //console.log(this.data)
  }

}
